#include "../Prec.h"


CBWorld::CBWorld(int x,int y)
{
  mGravity.x = x ;
  mGravity.y = y;
  mWidth=0;
  mHeight=0;
  mbLose=false;
  mCBworld2CocoProportionV=0;
  mCBworld2CocoProportionH=0;
}


CBWorld::~CBWorld(void)
{
}

void CBWorld::Tick(float deltatime,std::list<CCSprite*>& removelst)
{
  mbLose=false;
  Move(deltatime);
  Collision(removelst);

}

void CBWorld::Move(float deltatime)
{
  for(std::list<CBBody*>::iterator iter=mBodyLst.begin();iter!=mBodyLst.end();++iter)
  {
    CBBody* body = *iter;
    body->mMoved=false;
  }
  for(std::list<CBBody*>::iterator iter=mBodyLst.begin();iter!=mBodyLst.end();++iter)
  {
    CBBody* body = *iter;
    if(body->mMoved)
      continue;
    CCPoint force;
    CalcForce(body,force);
    body->Move(deltatime,force);
  }
}

void CBWorld::CalcForce(CBBody* body,CCPoint& force)
{
  InitCalc();
  body->CalcBodyForce(force);
}

void CBWorld::InitCalc()
{
  for(std::list<CBBody*>::iterator iter=mBodyLst.begin();iter!=mBodyLst.end();++iter)
  {
    CBBody* body = *iter;
    body->mCalced=false;
  }
}

void CBWorld::Collision(std::list<CCSprite*>& removelst)
{
  /*for(std::list<SCollision*>::iterator iter = mTempCollisionLst.begin();iter!=mTempCollisionLst.end();++iter)
    delete *iter;
  mTempCollisionLst.clear();*/

  std::list<CBBody*>::iterator iter=mBodyLst.begin();
  if(iter==mBodyLst.end()||(*iter)->mType!=EBT_Ball)
  {
    return ;
  }
  CBBall* curFlyBall = (CBBall*)*iter;
  if(curFlyBall->mForce!=false)
    return ;
  iter++;
  
  bool col = false;
  for(;iter!=mBodyLst.end();++iter)
  {
    CBBody* body = *iter;
    bool ret = body->CheckCollision(curFlyBall);
    if(ret)
    {
      col = true;
      curFlyBall->Collision(body);
      break;
    }
  }
  if(col)
  {
    InitCalc();
    curFlyBall->SameColor(curFlyBall->mColor,removelst);
    if(curFlyBall->mCircle.y<10)
      mbLose=true;
  }
}
